package com.csthink.auditlog.mq.producer;

import com.csthink.auditlog.domain.AuditLog;
import com.csthink.auditlog.enums.AuditLogBusinessEnum;
import com.csthink.auditlog.mq.payload.ESPayload;
import com.csthink.common.infrastructure.util.Jackson2Util;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-12
 */
@Slf4j
@Component
public class AuditLogProducer {

//    @Autowired
//    private AsyncProducerService asyncProducerService;

    @Value("${async.mq.publisher.topic.audit-log:}")
    private String asyncSearchTopic;

    public void produce(List<AuditLog> auditLogs, AuditLogBusinessEnum auditLogBusinessEnum) {
        if (auditLogBusinessEnum == null) {
            log.warn("Not set audit log business.");
            return;
        }
        if (CollectionUtils.isEmpty(auditLogs)) {
            log.debug("No audit logs need send to async search.");
            return;
        }
        if (StringUtils.isBlank(asyncSearchTopic)) {
            log.warn("Cannot send to async search as there isn't topic.");
            for (AuditLog auditLog : auditLogs) {
                log.info("{}", auditLog);
            }
            return;
        }

        String businessName = auditLogBusinessEnum.getBusinessName();
        if (StringUtils.isBlank(businessName)) {
            log.warn("Not found business name for service: {}", auditLogBusinessEnum);
            return;
        }

        List<ESPayload> payload = Lists.newArrayList();
        for (AuditLog auditLog : auditLogs) {
            payload.add(ESPayload.of("upsert", Jackson2Util.toMap(auditLog), System.currentTimeMillis()));
        }
        log.debug("payload:{}", payload);

//        Map<String, Object> extra = Maps.newHashMap();
//        extra.put("x-cst-business-name", businessName);

        // todo asyncmq
//        AsyncMQParam<List<ESPayload>> param = AsyncMQParam.<List<ESPayload>>builder()
//                .topicName(asyncSearchTopic)
//                .taskType("universal-index")
//                .extraInfo(extra)
//                .payload(payload)
//                .build();
//        asyncProducerService.sendAsyncTask(param);

        log.info("Send {}: {} audit logs to async search.", auditLogBusinessEnum, auditLogs.size());
    }
}
